package com.greenold.web.controller.system;

import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.greenold.common.core.redis.RedisCache;
import com.greenold.common.utils.http.HttpUtils;
import com.greenold.system.domain.SysUserRole;
import com.greenold.system.domain.WxChatCustomer;
import com.greenold.system.mapper.SysUserMapper;
import com.greenold.system.mapper.SysUserRoleMapper;
import com.greenold.system.mapper.WxChatCustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.greenold.common.constant.Constants;
import com.greenold.common.core.domain.AjaxResult;
import com.greenold.common.core.domain.entity.SysMenu;
import com.greenold.common.core.domain.entity.SysUser;
import com.greenold.common.core.domain.model.LoginBody;
import com.greenold.common.core.domain.model.LoginUser;
import com.greenold.common.core.text.Convert;
import com.greenold.common.utils.DateUtils;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.common.utils.StringUtils;
import com.greenold.framework.web.service.SysLoginService;
import com.greenold.framework.web.service.SysPermissionService;
import com.greenold.framework.web.service.TokenService;
import com.greenold.system.service.ISysConfigService;
import com.greenold.system.service.ISysMenuService;

import javax.annotation.Resource;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysUserMapper sysusermapper;
    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private WxChatCustomerMapper wxChatCustomerMapper;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
    
    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
    @PostMapping("/phoneLogin1")
    public AjaxResult phoneLogin1(@RequestBody Map<String, String> params) {
        String phoneCode = params.get("phoneCode");
        String loginCode = params.get("loginCode");
        if (phoneCode == null || loginCode == null) {
            return AjaxResult.error("缺少必要参数");
        }
        try {
            // 1 用 loginCode 获取 openid
            String sessionUrl = String.format(
                    "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                    "wx18ac00cf04b30715", "aa23ff50de810c9116639e1ddbe6a19a", loginCode
            );
            String sessionRes = HttpUtils.sendGet(sessionUrl);
            JSONObject sessionJson = JSONObject.parseObject(sessionRes);
            String openid = sessionJson.getString("openid");
            if (openid == null) {
                return AjaxResult.error("获取 openid 失败");
            }
            // 2 获取 access_token 并调用手机号接口
            String tokenUrl = String.format(
                    "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                    "wx18ac00cf04b30715", "aa23ff50de810c9116639e1ddbe6a19a"
            );
            String tokenRes = HttpUtils.sendGet(tokenUrl);
            String accessToken = JSONObject.parseObject(tokenRes).getString("access_token");

            String phoneUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            JSONObject postData = new JSONObject();
            postData.put("code", phoneCode);
            String phoneRes = HttpUtils.sendPost(phoneUrl, postData.toJSONString());
            JSONObject phoneInfo = JSONObject.parseObject(phoneRes).getJSONObject("phone_info");
        /*    {
                "errcode":0,
                    "errmsg":"ok",
                    "phone_info":{
                "phoneNumber":"13800138000",
                        "purePhoneNumber":"13800138000",
                        "countryCode":"86",
                        "watermark":{ "timestamp":1234567890, "appid":"wxXXXX" }
            }
            }*/
            String phoneNumber = phoneInfo.getString("purePhoneNumber");
            // 3 绑定手机号 + openid
            SysUser user = sysusermapper.selectUserByPhonenumber(phoneNumber);
            if (user == null) {
                user = new SysUser();
                user.setUserName("wx_" + phoneNumber);
                user.setPhonenumber(phoneNumber);
                user.setNickName("用户" + phoneNumber.substring(7));
                user.setPassword(SecurityUtils.encryptPassword("123456"));
                sysusermapper.insertUser(user);
                // 创建单个 SysUserRole 对象
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(user.getUserId());  // 新创建用户的ID
                userRole.setRoleId(107L);  // 微信用户角色ID，根据实际情况调整
                // 将用户角色关联信息插入数据库
                List<SysUserRole> userRoleList = Arrays.asList(userRole);
                sysUserRoleMapper.batchUserRole(userRoleList);
                WxChatCustomer customer = new WxChatCustomer();
                customer.setOpenId(openid);
                customer.setSysUserId(user.getUserId());
                customer.setMobile(phoneNumber);
                wxChatCustomerMapper.insertWxChatCustomer( customer);

            }
            // 4 返回数据
            String token = loginService.login(user.getUserName(), "123456", null, null);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("phoneNumber", phoneNumber);
//            ajax.put("openid", openid);
            ajax.put("token", token);
            ajax.put("userId", user.getUserId());
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("服务器异常");
        }
    }
}
